package org.jieshen.m1.d6;

import javafx.scene.shape.Path;

import java.util.ArrayDeque;
import java.util.Deque;


public class Solution {
    public String simplifyPath(String path) {
        Deque<String> d = new ArrayDeque<>();
        StringBuffer buffer = new StringBuffer();
        // /../
        for (int i = 0; i < path.length(); i++) {
            if (path.charAt(i) == '/') {
                continue;
            }
            int j = i + 1;
            while (j < path.length() && path.charAt(j) != '/') {
                j += 1;
            }
            //System.out.println("i,j " + i + " " + j);
            String item = path.substring(i, j);
            //System.out.println("item: " + item);
            if (item.equals("..")) {
                if (!d.isEmpty()) {
                    d.removeLast();
                }
                i = j;
                continue;
            }else if(item.equals(".")){
                i = j;
                continue;
            }
            d.addLast(item);

            i = j;
        }
        for (String s : d) {
            buffer.append('/' + s);
        }
        if (buffer.length() == 0) {
            buffer.append('/');
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        // 输入：path = "/a/./b/../../c/"
        // 输出："/c"
        //测试
        // /../

        // charAt越界怎么办
        String path = "/home//foo/";
        String s = new Solution().simplifyPath(path);
        System.out.println(s);


    }
}
